package com.example.park;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;
import com.example.park.Protocol;


import java.nio.charset.StandardCharsets;

public class RegisterActivity extends AppCompatActivity {

    private EditText usernameEditText, passwordEditText, confirmPasswordEditText;
    private EditText licensePlateEditText;
    private Button registerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        
        usernameEditText = findViewById(R.id.edit_username);
        passwordEditText = findViewById(R.id.edit_password);
        confirmPasswordEditText = findViewById(R.id.edit_confirm_password);
        licensePlateEditText = findViewById(R.id.edit_license_plate);
        registerButton = findViewById(R.id.register_button);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String confirmPassword = confirmPasswordEditText.getText().toString();
                String plate = licensePlateEditText.getText().toString();

                if (!LicensePlateValidator.isValid(plate)) {
                    Toast.makeText(RegisterActivity.this, "请输入有效车牌", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.equals(confirmPassword)) {
                    // 执行注册操作（这里只是示例，可以连接数据库保存用户信息）
                    //Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();

                    try {
                        JSONObject root = new JSONObject();
                        JSONObject message = new JSONObject();
                        message.put("username",username);
                        message.put("password",password);
                        message.put("plate",plate);

                        root.put("func",1);
                        root.put("message",message);

                        String jsonString = root.toString();
                        String package_ = Protocol.Encode(jsonString);
                        TcpClient.getInstance().sendMessage(package_);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    new Thread(() -> {
                        try {
                            String response = TcpClient.getInstance().receiveMessage();
                            if (response == null || response.isEmpty()) {
                                runOnUiThread(() ->
                                        Toast.makeText(RegisterActivity.this, "未收到服务器响应", Toast.LENGTH_SHORT).show()
                                );
                                return;
                            }

                            StringBuilder remaining = new StringBuilder();
                            String content = Protocol.Decode(response, remaining);

                            if (content == null || content.isEmpty()) {
                                runOnUiThread(() ->
                                        Toast.makeText(RegisterActivity.this, "服务器响应格式错误", Toast.LENGTH_SHORT).show()
                                );
                                return;
                            }

                            JSONObject json = new JSONObject(content);
                            int n = json.optInt("bool", 0);

                            if (n == 1) {
                                runOnUiThread(() -> {
                                    //Toast.makeText(RegisterActivity.this, "服务器回复: " + content, Toast.LENGTH_LONG).show();
                                    finish(); // 成功接收消息后返回登录页
                                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();


                                });
                            }
                            else if(n==2)
                            {
                                runOnUiThread(() -> {
                                    Toast.makeText(RegisterActivity.this, "用户名重复，请重新输入", Toast.LENGTH_SHORT).show();
                                });
                            }
                            else {
                                runOnUiThread(() -> {
                                    Toast.makeText(RegisterActivity.this, "注册失败或服务器拒绝", Toast.LENGTH_SHORT).show();
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(() ->
                                    Toast.makeText(RegisterActivity.this, "接收或解析服务器数据出错", Toast.LENGTH_SHORT).show()
                            );
                        }
                    }).start();

                    //接受消息
                    //finish(); // 返回登录页面
                    //Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RegisterActivity.this, "两次密码不匹配", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}
